package com.gxuwz.medical.web.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * @author 演示
 *
 */
public class AuthorFilter implements Filter {

	public void destroy() {
	}

	public void init(FilterConfig config) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		PermissionInterceptor permissionInterceptor = new PermissionInterceptor();
		// 获取HttpSession对象，判断是否登陆
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		req.setCharacterEncoding("utf-8");
		res.setContentType("text/html;charset=utf-8");
		res.setCharacterEncoding("utf-8");
		try {
			boolean loginHandle = permissionInterceptor.loginHandle(req, res);
			if (loginHandle == false) {
				res.sendRedirect(req.getContextPath() + "/loginPermission.jsp");
			} else {
				// 如果有下一个过滤器则跳转到下一个过滤器否则目标页面
				System.out.println("登录成功");
				String goURL = req.getServletPath();// (获取到地址不包括参数)
				System.out.println("拦截的地址为==" + goURL);

				// 判断参数是否为空，不null就获取参数
				if (req.getQueryString() != null) {

					Map<String, String[]> params = request.getParameterMap();
					String[] params1 = params.get("m");

					goURL += "?m=" + params1[0];// 只获取key=m的value值
					System.out.println("拦截带参数的地址为==" + goURL);
					boolean urlHandle = permissionInterceptor.urlHandle(req, res, goURL);
					if (urlHandle == true) {// 授权拦截成功
						chain.doFilter(request, response);
					} else {
						res.sendRedirect(req.getContextPath() + "/permission.jsp");
					}

				} else {
					boolean urlHandle = permissionInterceptor.urlHandle(req, res, goURL);
					if (urlHandle == true) {
						chain.doFilter(request, response);
					} else {
						res.sendRedirect(req.getContextPath() + "/permission.jsp");
					}
				}

			}
		} catch (

		Exception e) {
			// TODO: handle exception
		}

	}

}